package com.sskj.xyft.api;

import android.accounts.NetworkErrorException;

import com.google.gson.JsonSyntaxException;
import com.hjq.toast.ToastUtils;
import com.sskj.xyft.BasePresenter;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public abstract class SimpleHttpObserver<T> implements Observer<T> {

    private BasePresenter mPresenter;

    private boolean showLoading;

    public SimpleHttpObserver() {
    }

    public SimpleHttpObserver(BasePresenter presenter) {
        mPresenter = presenter;
    }

    public SimpleHttpObserver(BasePresenter presenter, boolean showLoading) {
        mPresenter = presenter;
        this.showLoading = showLoading;
    }

    @Override
    public void onSubscribe(Disposable d) {
        if (mPresenter != null) {
            if (showLoading && mPresenter.mView != null) {
                mPresenter.mView.showLoading();
            }
            mPresenter.addRequest(d);
        }
    }

    @Override
    public void onNext(T result) {
        if (mPresenter != null && mPresenter.mView != null) {
            onSuccess(result);
            onComplete();
        }
    }


    @Override
    public void onError(Throwable e) {
        onComplete();
        if (e instanceof NetworkErrorException) {

        } else if (e instanceof JsonSyntaxException) {

        } else if (e instanceof ServiceException) {
            onSuccess((T) ((ServiceException) e).getResult());
            ToastUtils.show(((ServiceException) e).getMsg());
        } else {

        }
    }

    @Override
    public void onComplete() {
        if (mPresenter != null && mPresenter.mView != null) {
            if (showLoading) {
                mPresenter.mView.hideLoading();
            }
        }
        mPresenter = null;
    }


    public abstract void onSuccess(T data);
}
